define(function(require, exports, module) {
    'use strict';

    var isEditMode = (SESSION.prj === 'canvas');

    var rk_userService = require('./services/2.0/rk_userService');
    var menuUtil = require('./utils/menuUtil');
    var formMgr = require('../platform/manager/formMgr');
    var dataMgr = require('../platform/manager/dataMgr');

    var isOpera = !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
    // Opera 8.0+ (UA detection to detect Blink/v8-powered Opera)
    var isFirefox = typeof InstallTrigger !== 'undefined'; // Firefox 1.0+
    var isSafari = Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0;
    // At least Safari 3+: "[object HTMLElementConstructor]"
    var isChrome = !!window.chrome && !isOpera; // Chrome 1+
    var isIE = /*@cc_on!@*/ false || !!document.documentMode; // At least IE6

    var rk = {
        DEFAULT_USER_ICON: rk_userService.DEFAULT_USER_ICON, //头像
        DEFAULT_GROUP_ICON: '/static/img/v3.0/group_default_ico.png', //群组
        DEFAULT_DEP_ICON: '/static/img/v3.0/group_detail_ico.png' //部门
    };

    rk = $.extend(rk, {
        isOpera: isOpera,
        isFirefox: isFirefox,
        isSafari: isSafari,
        isChrome: isChrome,
        isIE: isIE,
        isMac: navigator.platform.toUpperCase().indexOf('MAC') >= 0,
        isEditMode: isEditMode
    });

    rk.platform = platform; //判断平台版本



    if (seajs.data.dev || window.SESSION.prj == 'canvas') {
        window.__rk = rk;
    }

    //辅助方法
    (function() {
        var getOffset = function(el, type, isTarget) {
            var num, count = 0;
            if (true || el.css('position') == 'absolute') {
                num = parseInt(el.position()[type]);
                if ($.isNumeric(num)) count = count + num;
            } else {

            }
            num = parseInt(el.css('margin-' + type));
            if ($.isNumeric(num)) count = count + num;
            num = parseInt(el.css('padding-' + type));
            if ($.isNumeric(num) && !isTarget) count = count + num;
            num = parseInt(el.css('border-weight'));
            if ($.isNumeric(num)) count = count + num;
            return count;
        };
        var getAbsDistance = function(obj, type) {
            var parents = obj.parents();
            var totalLeft = 0;
            totalLeft = totalLeft + getOffset(obj, type, true);
            parents.each(function(i) {
                var el = $(this);
                totalLeft = totalLeft + getOffset(el, type, false);
            });
            return totalLeft;
        };
        rk.absolutePosition = function(elem) {
            return {
                left: rk.absoluteLeft(elem),
                top: rk.absoluteTop(elem)
            }
        };
        rk.absoluteLeft = function(elem) {
            return getAbsDistance(elem, 'left');
        };
        rk.absoluteTop = function(elem) {
            return getAbsDistance(elem, 'top');
        };
    })();

    //弹出类
    ;
    (function() {
        $.extend(rk, {
            version: 3.0,
            isDev: true,
            alert: function(msg, ok) {
                var me = this;
                require.async('page/tmpl/tpl_alert.tpl', function(tpl) {
                    me._alert(tpl, msg, ok);
                });
            },
            _alert: function(tpl, msg, ok) {
                if ($(document.body).find('#popup_content').size() == 0) {
                    $(document.body).append('<div id="popup_content"></div>');
                }
                var o = $(document.body).find('#popup_content');
                var html = rk.templateText(tpl, {
                    message: msg
                });
                o.html(html);
                var name = "rkAlertPopup";
                if ($('#popupLayer_' + name).is(':visible')) {
                    rk.closePopup(name, function() {
                        _alert();
                    });
                } else {
                    _alert();
                }

                function _alert() {
                    rk.popup({
                        name: name,
                        width: 430,
                        height: 210,
                        target: "popup_content",
                        success: function(sel) {
                            var win = $(sel);
                            var zindex = 99999;
                            win.css('z-index', zindex);
                            $('#popupLayerScreenLocker').css('z-index', zindex - 1);
                            win.find('[act="ok"]').click(function() {
                                rk.closePopup();
                            });
                            win.find('a.close').click(function() {
                                rk.closePopup();
                            });
                        },
                        afterClose: function() {
                            if ($.isFunction(ok))(ok)();
                        }
                    });
                }

            },
            confirm: function(arg0, arg1, arg2, arg3) {
                var me = this;
                require.async('page/tmpl/tpl_confirm.tpl', function(tpl) {
                    me._confirm({
                        msg: arg0,
                        tpl: tpl
                    }, arg1, arg2, arg3);
                });
            },
            _confirm: function(arg0, arg1, arg2, arg3) {
                var tpl = arg0.tpl;
                if ($(document.body).find('#popup_content').size() == 0) {
                    $(document.body).append('<div id="popup_content" style="display: none;"></div>');
                }
                var msg = arg0.msg;
                var okText, cancelText, okFn, cancelFn;
                var delayClose = false; //延时关闭，如果有的操作耗时较长，则需延时关闭
                if (typeof arg1 == 'object') {
                    okText = arg1.okText;
                    delayClose = !!arg1.delayClose;
                    okFn = arg2;
                    cancelFn = arg3;
                } else {
                    okText = rk.i18n('CONFIRM');
                    okFn = arg1;
                    cancelFn = arg2;
                }
                cancelText = rk.i18n('CANCEL');
                var o = $(document.body).find('#popup_content');
                var html = rk.templateText(tpl, {
                    title: rk.i18n('TIP'),
                    message: msg,
                    okText: okText,
                    cancelText: cancelText
                });
                o.html(html);
                var name = "rkAlertPopup";
                var winSel = '#popupLayer_' + name;
                if ($(winSel).is(':visible')) {
                    rk.closePopup(name, function() {
                        _confirm();
                    });
                } else {
                    _confirm();
                }

                function _confirm() {
                    rk.popup({
                        name: name,
                        width: 430,
                        height: 180,
                        target: "popup_content",
                        success: function(sel) {
                            var win = $(sel);
                            var zindex = 99999;
                            win.css('z-index', zindex);
                            $('#popupLayerScreenLocker').css('z-index', zindex - 1);
                            win.find('[act="cancel"]').click(function() {
                                rk.closePopup();
                                whichBtn = 'cancel';
                            });
                            win.find('[act="ok"]').click(function() {
                                if (delayClose) {
                                    (okFn)(winSel);
                                    whichBtn = false;; //afterClose中不再执行
                                } else {
                                    rk.closePopup();
                                    whichBtn = 'ok';
                                }
                            });
                            win.find('a.close').click(function() {
                                rk.closePopup();
                            });
                        },
                        afterClose: function() {
                            if (!whichBtn) return;
                            if (whichBtn == 'ok')
                                if ($.isFunction(okFn))(okFn)();
                            if (whichBtn == 'cancel')
                                if ($.isFunction(cancelFn))(cancelFn)();
                        }
                    });
                }
                var whichBtn;
            },
            closeConfirm: function() {
                rk.closePopup();
            },
            notice: function(msg, type) {
                type = type == 'sucess' ? '.sucess' : '.error';
                var speed = 400,
                    prompt = $('#notice_prompt'),
                    showCSS = {
                        top: 0,
                        opacity: 1
                    },
                    hideCSS = {
                        top: -150,
                        opacity: 0
                    };
                prompt.find('.sucess,.error').hide().filter(type).show().find('>p').text(msg);
                clearTimeout(rk.noticeTimer);
                prompt.stop(true, true).css(hideCSS).show().animate(showCSS, speed);
                rk.noticeTimer = setTimeout(function() {
                    prompt.animate(hideCSS, speed);
                }, 4000);
                //关闭
                if (!prompt.data('inited'))
                    prompt.find('span[class="hide"]').click(function() {
                        prompt.hide();
                    }).data('inited');
            },
            noticeError: function(msg) {
                rk.notice(msg, 'error');
            },
            noticeSuccess: function(msg) {
                rk.notice(msg, 'sucess');
            },
            dialog_resize_timer: null,
            dialog_resize_updated: false,
            dialog: function(opt) {
                var me = this;
                me.closeDialog();
                if (typeof opt == 'undefined') opt = {};
                var id = 'dialog';
                var min_width = 650;

                if ($('#' + id).size() > 0) {
                    $('#' + id).off().remove();
                }
                $(document.body).append('<div id="' + id + '"></div>'); //必须先构造一个div才能使用jquery dialog
                if (!opt.templateId && !opt.html) { //默认情况下，给默认高宽，在组件内部由controller初始化内部html
                    opt.html = '';
                    if (!opt.width) opt.width = min_width;
                    if (!opt.height) opt.height = 'auto';
                    popup();
                } else if (opt.templateId) {
                    require.async(opt.templateId, function(html) {
                        opt.html = rk.templateText(html, opt.templateData ? opt.templateData : {});
                        popup()
                    });
                } else {
                    popup();
                }

                function popup() {
                    var dialog = $(document.body).find('#' + id);
                    dialog.attr('title', (opt.title ? opt.title : ''))
                        .html(opt.html);

                    if (!opt.width) opt.width = min_width;

                    //这句话来自jquery-dialog源码，如果不加的话，当dialog中有multipeopleselecor时，其里面的<select>在FF中无法显示
                    $(document).data("ui-dialog-overlays", ($(document).data("ui-dialog-overlays") || 0) + 1);

                    dialog.dialog({
                        width: opt.width,
                        height: opt.height,
                        minHeight: 300,
                        maxHeight: 600,
                        modal: true,
                        draggable: true,
                        resizable: false,
                        position: {
                            my: "center",
                            at: "center",
                            of: window
                        },
                        open: function() {
                            $('.ui-widget-overlay').on('click', function(e) {
                                e.stopPropagation()
                            }).on('mousedown', function(e) {
                                e.stopPropagation()
                            }).on('mouseup', function(e) {
                                e.stopPropagation()
                            });
                            $(document.body).css('overflow', 'hidden');
                        },
                        close: function() {
                                $(document.body).css('overflow', 'auto');
                                me.closeDialog({
                                    close: function() {
                                        if ($.isFunction(opt.close))(opt.close)();
                                    }
                                });
                            }
                            //buttons: buttons
                    });

                    var winHeight = $(window).height();
                    var hiddenTop = winHeight;

                    dialog.attr('popup_animate', true);
                    // dialog.css('z-index', '1000'); //基准值
                    dialog.parent().css({
                        top: -1 * hiddenTop + 'px'
                    });

                    window.setTimeout(function() {
                        var pHeight = dialog.parent().outerHeight();
                        var top = (winHeight > pHeight) ? (winHeight - pHeight) / 2 : 0;
                        top = top - 20; //过度效果更好
                        dialog.parent().animate({
                            "top": "+=" + (top + hiddenTop) + "px"
                        }, "fast", function() {
                            dialog.removeAttr('popup_animate');
                            rk.repositionDialog(true);
                        });
                    }, 300);

                    //结构：
                    // pg-dialog-header
                    // pg-dialog-body <---滚动条在此
                    //    pg-dialog-content
                    // pg-dialog-footer

                    var parent = dialog.parent();

                    parent.addClass('pg-dialog');
                    if (opt.title === false) {
                        parent.find('>.ui-dialog-titlebar').remove();
                    } else {
                        parent.find('>.ui-dialog-titlebar').addClass('pg-dialog-header');
                    }

                    dialog.addClass('pg-dialog-body');
                    dialog.css('overflow', 'hidden');
                    parent.find('>.ui-dialog-buttonpane').off().remove();
                    dialog.html('<div class="pg-dialog-content">' + dialog.html() + '</div>');

                    if (opt.footer === false) {

                    } else {
                        parent.append('<div class="pg-dialog-footer pop-up-bottom">' +
                            '<div class="pop-up-footer-tools"></div>' +
                            '<div class="pop-up-button"></div>' +
                            '</div>');

                        var footer = parent.find('>.pg-dialog-footer');
                        if (opt.footer && opt.footer.toolbar) {
                            footer.find('>.pop-up-footer-tools').html(opt.footer.toolbar);
                        }
                        footer.find('>.pop-up-button').html(getDialogFooterHtml(opt.footer));
                    }

                    if (opt.success) {
                        (opt.success)(dialog.find('>.pg-dialog-content'), parent.find('>.pg-dialog-footer'));
                        me.repositionDialog();
                    }
                    if (!me.dialog_resize_updated)
                        $(window).resize(function() {
                            me.repositionDialog();
                            me.dialog_resize_updated = true;
                        });
                    me.repositionDialog();
                    $('#dialog').beScroll();
                }
            },
            closeDialog: function(opt) {
                var me = this;
                if (typeof opt == 'undefined') opt = {};
                var id = 'dialog';
                var dialog = $(document.body).find('>.ui-dialog > #' + id);
                if (dialog.size() > 0) {
                    dialog.dialog('close');
                    dialog.parents('ui-dialog:first').hide();
                    $(document.body).css('overflow', 'auto');
                    if (opt.close) {
                        (opt.close)();
                    }
                    $(document.body).css('overflow-y', me.bodyoverflow);
                    //延时以改善关闭用户体验（如果dialog结构过于复杂，在remove方法中需要处理的节点也会较多）
                    window.setTimeout(function() {
                        dialog.remove();
                        me._afterPopupClose();
                    }, 50);
                }
            },
            _afterPopupClose: function() {
                $('>.ui-dialog, .pg-dialog').off().remove();
                //关闭rkDialog时不删除以下组件
                // $(document.body).find('>.facebook-auto').off().remove();
                // $(document.body).find('>.ui-datepicker').off().remove();
                // $(document.body).find('>.ui-timepicker').off().remove();
            },
            repositionDialog: function(now) {
                if (typeof now != 'undefined') now = false;
                var me = this;
                var id = 'dialog';
                var dialog = $('#' + id);
                clearTimeout(me.dialog_close_timer);
                if (dialog.attr('popup_animate')) return; //仍处在弹出动画中
                if (now) {
                    me._repositionDialog();
                } else {
                    me.dialog_close_timer = setTimeout(function() {
                        me._repositionDialog();
                    }, 30);
                }
            },
            bodyoverflow: 'auto',
            _repositionDialog: function() {
                var me = this;
                var id = 'dialog';
                var dialog = $('#' + id);
                if (dialog.size() == 0 || !dialog.is(':visible')) return;

                //me.bodyoverflow = $(document.body).css('overflow-y');
                $(document.body).css('overflow-y', 'hidden')
                    // dialog.dialog("option", "height", 'auto');
                    // dialog.unScroll().beScroll();

                var scrollDisplayed = dialog.find('.mCSB_scrollTools_vertical:first').is(':visible');
                if (!scrollDisplayed) {
                    //dialog.dialog("option", "height", 'auto');
                    //return;  
                }

                var h_head = dialog.prev('.ui-dialog-titlebar').outerHeight(true);
                var h_body = dialog.find('.mCSB_container').height();
                var h_foot = dialog.next('.pg-dialog-footer').outerHeight(true);

                var h_total = h_head + h_body + h_foot;
                var h_win = $(document.body).height();

                var doResize = false;
                if (h_total > h_win) {
                    dialog.dialog("option", "height", h_win);
                    doResize = h_win;
                } else {
                    doResize = h_total;
                }
                if (doResize) {
                    var new_height = h_win;
                    if ($.isNumeric(doResize)) {
                        new_height = doResize + 3;
                    }
                    dialog.dialog('option', 'height', new_height);

                    if (dialog.isScroll()) {
                        dialog.find('.mCustomScrollBox:first').css('max-height', ''); //注意：不可以用unscroll方法，因为会造成富文本编辑器等控件丢失数据
                    }
                    dialog.beScroll();
                }
                dialog.dialog("option", "position", $('#' + id).dialog("option", "position"));
            },
            popup: function(opt) {
                var success = opt.success ? opt.success : function() {};
                if ($('.ui-dialog:visible').size() > 0) { //解决跟dialog冲突（当第二层dialog弹出第三层popupLayers时，第三层中的所有input和textarea都无法获得焦点或输入）的问题
                    $('.ui-dialog:visible').find('a[href*="javascript:"]').each(function(i, a) {
                        var a = $(this);
                        var href = a.attr('href');
                        a.attr('tempHref', href).removeAttr('href');
                    });
                }
                opt.success = function() {
                    var popupId = 'popupLayer_' + opt.name;
                    var sel = '#' + popupId;
                    var popup = $(sel);
                    (success)(sel);
                }
                var beforeClose;
                if (opt.beforeClose) beforeClose = opt.beforeClose;
                opt.beforeClose = function() {
                    if ($('.ui-dialog:visible').size() > 0) { //解决跟dialog冲突（当第二层dialog弹出第三层popupLayers时，第三层中的所有input和textarea都无法获得焦点或输入）的问题
                        $('.ui-dialog:visible').find('a[tempHref]').each(function(i, a) {
                            var a = $(this);
                            var href = a.attr('tempHref');
                            a.attr('href', href).removeAttr('tempHref');
                        });
                    }
                    if (beforeClose)(beforeClose)();
                }
                $.openPopupLayer(opt);
            },
            closePopup: function(arg, afterClose) {
                var me = this;
                $.closePopupLayer(arg, afterClose);
                //me._afterPopupClose();
            },
            //提交数据
            post: function(url, data, callback) {
                var me = this;
                if (rk.oa && rk.oa.getRequestUrl(url)) {
                    url = rk.oa.getRequestUrl(url);
                }
                var ret = $.post(url, data, function(data) {
                    me._filtResp(data); //缓存数据中的有用数据
                }, "json");
                ret.done(function(data) {
                    if (typeof callback != 'undefined')(callback)(data); //执行回调方法       
                });
                return ret;
            },
            //获得资源
            get: function(url, data, callback) {
                var me = this;
                if (rk.oa && rk.oa.getRequestUrl(url)) {
                    url = rk.oa.getRequestUrl(url);
                }
                var ret = $.get(url, data, function(data) {
                    me._filtResp(data); //缓存数据中的有用数据
                }, "json");
                ret.done(function(data) {
                    if (typeof callback != 'undefined')(callback)(data); //执行回调方法       
                });
                return ret;
            },
            _filtResp: function(data) {
                if (data && data.data) {
                    data = data.data;
                    if (data.currencyUnit) rk.currencyUnit = data.currencyUnit;
                    if (data.users) rk_userService.appendUserInfo(data.users);
                }
            },
            templateText: function(tpl_content, data) {
                var datas = $.makeArray(arguments).slice(1),
                    data = $.extend.apply($, [true, {}].concat(datas));
                return template.render(tpl_content)(data || {});
            },
            htmlEscape: function(s) {
                var type = typeof s;
                if (!s || type != 'string') return s;
                return (s + '').replace(/&/g, '&amp;')
                    .replace(/</g, '&lt;')
                    .replace(/>/g, '&gt;')
                    .replace(/'/g, '&#039;')
                    .replace(/"/g, '&quot;')
                    .replace(/\n/g, '<br />');
            },
            render: function(tempStr, data) {
                if (typeof data == 'undefined') data = {};
                return template.render(tempStr, data, {}); //桥接artTemplate
            },
            log: function() {
                console.log.apply(console, arguments);
            },
            debug: function() {
                console.debug.apply(console, arguments);
            },
            showBusy: function(elem) {

            },
            whereru: function(elem) {
                $(elem).css('border', '2px solid red')
            },
            validatepage: function() {
                var ids = $('*[id]');

                $('div').css({
                    'border': '2px solid red',
                    padding: '2px',
                    margin: '2px'
                });
                $('span').css({
                    'border': '2px solid orange',
                    padding: '2px',
                    margin: '2px'
                });
                $('li').css({
                    'border': '1px solid green',
                    padding: '2px',
                    margin: '2px'
                });
                $('section').css('border', '8px dashed black');
                var hasConflict = false;
                $.each(ids, function(i, el) {
                    el = $(el);
                    var id = el.attr('id');
                    if ($('#' + id).size() > 1) {
                        hasConflict = true;
                        console.error('DUPLICATED ID: ' + id)
                    }
                });
                console.log('Id ELEM SIZE: ' + ids.size() + (hasConflict ? '' : ', NO CONFLICT.'));
            },
            getUrlParam: function(name) {
                name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
                var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
                    results = regex.exec(location.search);
                return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
            },
            changeUrlParam : function(url, arg, arg_val){
                var hostAndSearch = url.split('?');
                var host = hostAndSearch[0]
                var search = hostAndSearch[1] ? hostAndSearch[1] : '';
                var paramArray = search.split('&');
                var newParamArray = new Array();
                paramArray.forEach(function(item, index){
                    var tmp = item.split('=');
                    var paramName = tmp[0] ? tmp[0].trim() : "";
                    var paramValue = tmp[1] ? tmp[1].trim() : '';

                    if(paramName == arg){
                        item = arg + "=" + arg_val;
                    }
                    newParamArray.push(item);
                })

                return host + "?" + newParamArray.join('&');

               /* var pattern = arg +'=([^&]*)'; 
                var replaceText = arg+'='+arg_val; 
                if(url.match(pattern)){ 
                    var tmp='/('+ arg+'=)([^&]*)/gi'; 
                    tmp=url.replace(eval(tmp),replaceText); 
                    return tmp; 
                }else{ 
                    if(url.match('[\?]')){ 
                        return url+'&'+replaceText; 
                    }else{ 
                        return url+'?'+replaceText; 
                    } 
                } 
                return url+'\n'+arg+'\n'+arg_val; */
            },
            eachUrlParam: function(fn) {
                var search = location.search;
                if (search) {
                    search = search.replace('?', '');
                    var arr = search.split('&');
                    for (var i = 0, len = arr.length; i < len; i++) {
                        var pair = arr[i];
                        var ps = pair.split('=');
                        var name = ps[0];
                        var value = ps[1];
                        if (name)(fn)(name, value);
                    }
                }
            },
            getDetailUrl: function() {

            },
            openWin: function(url, param, ctrlPath, appName) {
                var paramUrl = "";
                var paramString;
                if (ctrlPath) {
                    paramUrl += "&cp=" + ctrlPath;
                }
                if (appName) {
                    paramUrl += "&a=" + appName;
                }
                if (param) {
                    paramString = JSON.stringify(param);
                    paramUrl += "&param=" + paramString;
                }
                if (paramUrl) {
                    paramUrl = paramUrl.substr(1, paramUrl.length - 1);
                }
                window.open(url + "?" + paramUrl);
            },
            replaceStr: function(str, find, replace) {
                return str.replace(new RegExp(find, 'g'), replace);
            },
            lang: function(langId) {
                var args = [langId];
                //如果有其他参数的话：
                if (arguments.length > 1)
                    for (var i = 1; i < arguments.length; i++) {
                        args.push(arguments[i]);
                    }
                    //转换为text
                var text = $.i18n.apply($.i18n, args);
                //if(false)
                if (text && text.indexOf('#') >= 0) {
                    var arr = text.match(/(?:#){1}(?:[a-zA-Z0-9_@$%^~&*-]){1,}(?:#){1}/ig);
                    if (arr && arr.length > 0) {
                        var sessionKeywords = window.SESSION.keywords;

                        for (var i = 0, len = arr.length; i < len; i++) {
                            var key = arr[i];
                            var kw = key.substring(1, key.length - 1);
                            if (sessionKeywords[kw]) text = rk.replaceStr(text, key, $.i18n(sessionKeywords[kw]));
                        }
                    }
                }
                return text;
            },
            i18n: function() {
                return rk.lang.apply(rk, arguments);
            },
            i18nHtml: function(html) {
                return rk.templateText(html);
            },
            showPageView: function(panelId, title) {
                if (typeof title != 'undefined') rk.setTitle(title);
                if (panelId == 'rk' || panelId == 'crm' || panelId == 'oa') panelId = panelId + '-panel'; //短名
                var panel = $('#' + panelId);
                panel.parent().removeClass('page-warpper-panel-inner');
                var hidepanel = '';
                if (panelId.indexOf('crm') >= 0) {
                    $('#rk-panel').hide();
                }
                if (panelId.indexOf('rk') >= 0) {
                    $('#crm-panel').hide();
                    //panel.parent().addClass('page-warpper-panel-inner');
                }
                panel.show();
                //if(panelId == 'rk-panel') panel.beScroll();
                return panel;
            },
            foldLeftMenu: function() {
                $('#pageleft').pageLeftCtrl('fold');
            },
            unfoldLeftMenu: function() {
                $('#pageleft').pageLeftCtrl('unfold');
            },
            delegateMenu: function(opt) {
                var args = arguments;
                menuUtil.connect(opt);
            }
        });

        function getDialogFooterHtml(buttonsConf) {
            if ($.isArray(buttonsConf)) {
                var html = '';
                for (var i = 0; i < buttonsConf.length; i++) {
                    var btn = buttonsConf[i];
                    if (btn.color) btn.className = 'pg-btn-' + btn.color;
                    if (btn == 'ok') html = html + '<a act="ok" class="pg-btn-blue" href="#">' + rk.i18n('CONFIRM') + '</a>';
                    if (btn == 'cancel') html = html + '<a act="cancel" class="pg-btn-white" href="#">' + rk.i18n('CANCEL') + '</a>';
                    if (btn == 'submit') html = html + '<a act="submit" class="pg-btn-blue" href="#">' + rk.i18n('SUBMIT') + '</a>';
                    if (btn == 'save') html = html + '<a act="save" class="pg-btn-blue" href="#">' + rk.i18n('SAVE') + '</a>';
                    if (btn == 'update') html = html + '<a act="update" class="pg-btn-blue" href="#">' + rk.i18n('UPDATE') + '</a>';
                    if (btn && btn.act) {
                        html = html + '<a act="' + btn.act + '" class="' + (btn.className ? btn.className : 'pg-btn-blue') + '" ' + (btn.visible ? '' : 'style="display:none;"') + ' href="javascript:;">' + btn.text + '</a>';
                    }
                }
                return html;
            } else if (buttonsConf && buttonsConf.buttons) {
                return getDialogFooterHtml(buttonsConf.buttons);
            } else {
                return buttonsConf;
            }
        }
    })();
    //页面相关
    ;
    (function() {
        $.extend(rk, {
            //获得context的url
            setTitle: function(title) {
                $('#pagehead').pageHeadCtrl('setTitle', title);
            },
            setTitleHtml: function(html) {
                $('#pagehead').pageHeadCtrl('setTitle', html, true);
            }
        });
    })();
    //app名称转换
    ;
    (function() {
        var namemap = {
            "page": "page",
            "crm": "crm",
            "oa": "oa",
            "rs": "resource",
            "wr": "workreport",
            "od": "order",
            "rsc": "rescenter",
            "feed": "feed",
            "apr": "approval",
            "lead": "lead",
            "acc": "account",
            "case": "case",
            "ctc": "contact",
            "opp": "opportunity",
            "ctr": "contract",
            "sea": "highsea",
            "task": "task",
            "slu": "solution",
            "sch": "schedule",
            "clg": "colleague"
        };
        var rev_namemap = null;

        $.extend(rk, {
            //获取app的全名
            getFullAppName: function(alias) {
                var fullname = namemap[alias];
                return fullname ? fullname : alias;
            },
            //获取app的缩写
            getShortAppName: function(fullname) {
                var me = this;
                if (rev_namemap == null) rev_namemap = _revert();
                return rev_namemap[fullname];
            }
        });

        var _revert = function() {
            rev_namemap = {};
            for (var alias in namemap) {
                rev_namemap[namemap[alias]] = alias;
            }
            return rev_namemap;
        };

    })();
    //事件代理
    ;
    (function() {
        var pool = {};
        $.extend(rk, {
            onResize: function(elem) {
                var uid = elem.attr('id');
                if (!uid) {
                    elem.uniqueId();
                    uid = elem.attr('id');
                }
                pool[uid] = true;
                return elem;
            }
        });
        var timer;
        $(window).on('resize.rk', function(e) {
            window.clearTimeout(timer);
            timer = window.setTimeout(function() {
                for (var uid in pool) {
                    if ($('#' + uid).size() > 0) {
                        try {
                            $('#' + uid).trigger('handleGlobalResize');
                        } catch (e) {
                            throw new Error('method error within #' + uid);
                        }
                    } else {
                        pool[uid] = null;
                        delete pool[uid];
                    }
                }
            }, 100);

        });
    })();
    //moment
    ;
    (function() {
        rk.moment = {};
        rk.moment.floor = function(mom) {
            mom.hours(0);
            mom.minutes(0);
            mom.seconds(0);
            return mom;
        };
    })();

    //为arttemplate写的helper
    (function() {
        template.helper('templateText', function(tpl, data) {
            if (!tpl) return '';
            return rk.templateText(tpl, data);
        });
        template.helper('dateFormat', function(date, format) {
            return moment(date).format(format);
        });
        template.helper('htmlEscape', function(s) {
            return rk.htmlEscape(s);
        });
        //法1，{{'wr_name' | i18n}}
        //法2，{{'wr_name' | i18n: 'big', $string(big), 5000 }}
        template.helper('i18n', function(langId) {
            var args = [langId];
            //如果有其他参数的话：
            if (arguments.length > 1)
                for (var i = 1; i < arguments.length; i++) {
                    args.push(arguments[i]);
                }
                //转换为text
            var text = rk.i18n.apply(rk, args);
            return text;
        });
        template.helper('getDefaultIcon', function(type) {
            if (type == "detail") {
                return rk.DEFAULT_DEP_ICON;
            } else if (type == "table") {
                return rk.DEFAULT_GROUP_ICON;
            } else {
                return rk.DEFAULT_USER_ICON;
            }
        });
        // template.helper('getDetailUrl', function(param, ctrlPath, appName) {
        //     var url = '/final.action';
        //     var paramUrl = "";
        //     var paramString;
        //     if (ctrlPath) {
        //         paramUrl += "&cp=" + ctrlPath;
        //     }
        //     if (appName) {
        //         paramUrl += "&a=" + appName;
        //     }
        //     if (param) {
        //         //paramString = JSON.stringify(param);
        //         paramUrl += "&param=" + param;
        //     }
        //     if (paramUrl) {
        //         paramUrl = paramUrl.substr(1, paramUrl.length - 1);
        //     }
        //     return url + "?" + paramUrl;
        // });
    })();

    //formatText，文字格式化用
    ;
    (function() {
        rk.formatText = function(value, type, format, opt) {
            if (typeof opt == 'undefined') opt = {};
            var text = value;
            if (typeof type == 'object') type = type.itemType ? type.itemType : type.itemTypeEntry;
            switch (type) {
                case 7:
                    if (typeof format == 'undefined') format = 'YYYY-MM-DD';
                    text = moment(value).format(format);
                    break;
                default:
                    text = value;
            }
            return text;
        };
        template.helper('fmt', function(value, type, format) {
            return rk.formatText(value, type);
        });
    })();


    //belong查询
    (function() {
        var belongs = [{
            id: "-100",
            name: "wanxue"
        }, {
            id: "1",
            name: "account"
        }, {
            id: "10",
            name: "competitor"
        }, {
            id: "105",
            name: "attendance"
        }, {
            id: "11",
            name: "lead"
        }, {
            id: "111",
            name: "activityrecord"
        }, {
            id: "112",
            name: "visitcollect"
        }, {
            id: "113",
            name: "trackanalysis"
        }, {
            id: "116",
            name: "checkinmap"
        }, {
            id: "12",
            name: "case"
        }, {
            id: "13",
            name: "approval"
        }, {
            id: "15",
            name: "contract"
        }, {
            id: "2",
            name: "contact"
        }, {
            id: "20",
            name: "colleague"
        }, {
            id: "21",
            name: "solution"
        }, {
            id: "25",
            name: "workreport"
        }, {
            id: "28",
            name: "workreportstatistic"
        }, {
            id: "3",
            name: "opportunity"
        }, {
            id: "30",
            name: "task"
        }, {
            id: "31",
            name: "schedule"
        }, {
            id: "34",
            name: "goal"
        }, {
            id: "35",
            name: "order"
        }, {
            id: "4",
            name: "product"
        }, {
            id: "40",
            name: "group"
        }, {
            id: "45",
            name: "rescenter"
        }, {
            id: "50",
            name: "department"
        }, {
            id: "51",
            name: "forecast"
        }, {
            id: "52",
            name: "dashboard"
        }, {
            id: "53",
            name: "report"
        }, {
            id: "54",
            name: "salesanalysis"
        }, {
            id: "6",
            name: "campaign"
        }, {
            id: "60",
            name: "feed"
        }, {
            id: "61",
            name: "privatemessage"
        }, {
            id: "62",
            name: "notice"
        }, {
            id: "63",
            name: "expense"
        }, {
            id: "64",
            name: "expenseaccount"
        }, {
            id: "66",
            name: "agent"
        }, {
            id: "67",
            name: "terminal"
        }, {
            id: "68",
            name: "visit"
        }, {
            id: "69",
            name: "payment"
        }, {
            id: "9",
            name: "partner"
        }, {
            id: "999",
            name: "customize"
        }];

        var belongMap = {};
        belongs.forEach(function(o, i) {
            belongMap[o.id] = belongMap[o.name] = o;
        });

        // keywords: {"visit":"拜访记录","payment":"回款记录","account":"客户","contact":"联系人","opportunity":"销售机会","expenseaccount":"报销单","product":"产品","agent":"代理商","campaign":"市场活动","terminal":"终端","partner":"合作伙伴","competitor":"竞争对手","lead":"销售线索","case":"服务个案","approval":"审批","contract":"合同","solution":"解决方案","colleague":"通讯录","workreport":"工作报告","workreportstatistic":"工作报告统计","schedule":"日程","task":"任务","goal":"目标","order":"订单","wanxue":"万学精确营销管理模型","activityrecord":"活动记录","group":"群组","attendance":"考勤统计","rescenter":"知识库","forecast":"销售预测","department":"部门","salesanalysis":"销售绩效分析","trackanalysis":"轨迹分析","report":"报表","visitcollect":"拜访统计","dashboard":"仪表盘","expense":"费用","notice":"消息","privatemessage":"企业微信","feed":"动态","highsea":"客户公海池","leadhighsea":"销售线索公海池","cas":"服务个案"},
        if (window.SESSION && window.SESSION.keywords) {
            var keywords = SESSION.keywords;
            //keywords.checkinmap='签到地图';
            //keywords[116]='checkinmap';
            Object.keys(keywords).forEach(function(key) {
                if (belongMap[key]) {
                    belongMap[key].label = keywords[key];
                }
            });
        }
        // console.log(belongs);

        rk.queryBelong = function(keyword, item) {
            var belong = belongMap[keyword];
            if (arguments.length < 2) {
                return belong;
            }
            return belong ? belong[item] : belong;
        };

    })();

    // system id 查询
    (function() {
        var oSysId = {
            'common': {
                /*
                 ***********************  common  ********************
                 */
                // 公司级别
                'company': 8,
                //平台(系统)级别
                'platform': 9,
                //系统菜单
                'menu': 5,
            },
            'base': {
                /*
                 *********************  base  ***********************
                 */
                //feed
                'feed': 10,
                //评论
                'comment': 11,
                //profile    (liuyan)
                'profile': 12,
                //profile  reply     (reply liuyan)
                'profile_reply': 13,
                //group
                'group': 14,
                //colleague
                'colleague': 20,
            },
            'apps': {
                /*
                 ********************  apps  **************************
                 */
                'message': 501, //消息
                'file': 502, //文件
                'question': 503, //提问
                'praise': 504, //赞扬
                'blog': 505, //博客
                'private_message': 506, //私信
                'activity_stream': 507, //系统动态
                'work_report': 601, //工作日报
                'approval': 602, //审批
                'flow_category': 603, //流程类别 （上传用到了）
                'apply': 604, //申请（上传用到了）
                'activity_record': 605,
                'task': 606, //工作日报
                'activity_record_new': 607,
                'schedule': 608, //日程
                'flow': 609, //审批流保存时生成唯一的流水号
                'sign_in': 611, //签到
                'sales_goal': 612, //销售目标
                'expense': 613, //费用管理
                'agent': 614, //代理商
                'terminal': 615, //终端
                'visit_plan': 616, //巡访计划
                'visit_record': 617, //巡访记录
                'expense_account': 618, //报销单
                'attendance': 619, //考勤
                'feedback': 620, //意见反馈
                //crms
                'case': 508, //个案
                'case_transfer': 509, //
                'account': 510, //客户
                'opportunity': 511, //商机
                'product': 512, //产品
                'industry': 513, //行业
                'competitor': 514, //竞争对手
                'partner': 515, //合作伙伴
                'campaign': 516, //商场活动
                'product_family': 517, //
                'contact': 518, //联系人
                'case_solution': 520, //解决方案
                'contract': 521, //合同
                'lead': 522, //线索
                'high_sea': 523, //公海
                'order': 524, //订单
                'customize': 999, //自定义
            },
            'as': {
                //activity streams
                'customer': 1001, //客户
                'customer_external': 1002, //客户vip空间
                'contact': 1003, //联系人
                'opportunity': 1004, //销售机会
                'campaign': 1005, //市场活动
                'lead': 1006, //销售线索
                'case': 1007, //服务个案
                'competitor': 1008, //竞争对手
                'partner': 1009, //合作伙伴
                'file': 1010, //文件
                'member': 1011, //相关员工
                'task': 1012, //任务
                'notes': 1013, //交往记录
                'product_family': 1014, //产品线
                'product': 1015, //产品
                'contract': 1016, //合同
                'schedule': 1017, //日程
                'order': 1018, //订单
                'owner_member': 1019, //负责员工
                'customize': 1020, //自定义活动流
                'expense': 1021, //费用
                'agent': 1022, //代理商
                'terminal': 1023, //终端
                'expense_account': 1024, //报销单
            }
        };
        var idNameMap, arCates = Object.keys(oSysId);

        rk.querySysId = function(cate, name) {
            var id = Number(cate);
            return arguments.length == 1 && !isNaN(id) ? rk.queryNameById(id) : rk.queryIdByName(cate, name);
        };
        rk.queryIdByName = function(cate, name) {
            if (!oSysId[cate] || !oSysId[cate][name]) {
                return void(0);
            }
            return oSysId[cate][name];
        };
        rk.queryNameById = function(id) {
            if (!idNameMap) {
                idNameMap = makeIdNameMap();
            }
            return idNameMap[id];
        };

        function makeIdNameMap() {
            var rslt = {};
            arCates.forEach(function(cate) {
                Object.keys(oSysId[cate]).forEach(function(name) {
                    rslt[oSysId[cate][name]] = [cate, name].join('.');
                });
            });
            return rslt;
        }

    })();

    //加载所有的语言资源
    (function() {
        var language = window.SESSION.user.language;
        // var isDev = seajs.data.dev;
        $.i18n({
            locale: language
        });
        //var locale
        //var langJson = require('core/i18n/all_{locale}');
        var langJson = require('../core/i18n/all_zh-cn');
        $.i18n().load(langJson, language);
    })();

    formMgr.setRk(rk);
    dataMgr.setRk(rk);

    (function(global, rk) {
        //*****单文档内单实例使用，暂不保证多实例的正确性*****
        //跨域通信的解决方案，对postMessage进行简单的包装
        //targetOrigin：对与当前页面进行通信的origin的限制

        /* 在外层页面需要 setTargetWindow ，而在iframe里不需要 */
        // var cable = new Cable('http://crm-dev11rs.ingageapp.com');
        // cable.setTargetWindow($('#iframe_cable')[0].contentWindow);
        // cable.registMessageHandler(function(evt) {
        //     $('<li>').text(JSON.stringify(evt.data)).appendTo('ul.output');
        // });

        var Cable = rk.Cable = function(targetOrigin) {
            this.handlers = [];
            this.targetOrigin = targetOrigin || location.origin;
            this.bindMessageHandler();
        }
        Cable.prototype = {
            //设置目标window对象，可以是iframe的contentWindow、open返回的win实例
            setTargetWindow: function(targetWindow) {
                this.targetWindow = targetWindow;
                this._shakeHand_();
            },
            //进行握手连接
            _shakeHand_: function() {
                var that = this;
                this.shTimer = setInterval(function() {
                    that.postMessage('_shakeHand_:send', that.targetOrigin);
                }, 50)
            },
            bindMessageHandler: function() {
                var that = this;
                global.addEventListener('message', function(evt) {
                    //对origin进行检查，非法源的事件不响应
                    if (evt.origin !== that.targetOrigin) {
                        return;
                    }
                    if (evt.data === '_shakeHand_:send') {
                        if (!that.targetWindow) {
                            that.targetWindow = evt.source;
                            that.postMessage('_shakeHand_:feedback', that.targetOrigin);
                        }
                        return;
                    }
                    if (evt.data === '_shakeHand_:feedback') {
                        clearInterval(that.shTimer);
                        return;
                    }
                    //处理所有注册了的事件处理方法
                    that.handlers.every(function(handler) {
                        return handler(evt);
                    });
                }, false);
            },
            //注册接收消息的事件处理方法
            registMessageHandler: function(handler) {
                this.handlers.push(handler);
            },
            //取消注册接收消息的事件处理方法
            unRegistMessageHandler: function(handler) {
                this.handlers = this.handlers.fitler(function(fn) {
                    return fn !== handler;
                });
            },
            //向targetWindow发送消息
            postMessage: function(data) {
                if (this.targetWindow) {
                    return !this.targetWindow.postMessage(data, this.targetOrigin);
                }
            }
        };
    })(window, rk);

    //用法1，_rk.runDesignerMethod('designer.canvas.handleOnDataLoad', OriginalFormJson);
    //用法2，_rk.runDesignerMethod('#westPanel', 'westPanel', 'getItemInfo');
    rk.runDesignerMethod = function(methodName, arg1, arg2, arg3, arg4, arg5){
        if(!rk.isEditMode)return;
        if(!parent.__designer)return;        
        var args = $.makeArray(arguments);
        var fn;
        if(methodName.indexOf('#') === 0){
            args.shift();
            args.shift();
            return parent.$(methodName)[arg1](arg2, arg3, arg4, arg5);//TODO, 重构为arguments,.apply(this, args)//
        }else{
            eval('fn = parent.__' + methodName);
            args.shift();
            if(fn)return fn.apply(this, args)
        }        
    };

    module.exports = rk;
});
